package com.heima.aspect;

import com.heima.annotation.AutoFill;
import com.heima.constant.AutoFillConstant;
import com.heima.context.BaseContext;
import com.heima.enums.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Slf4j
@Aspect
public class AutoFillAspect {
    @Pointcut("execution(* com.heima.mapper..*.*(..)) && @annotation(com.heima.annotation.AutoFill)")
    public void pointCut() {

    }

    @Before("pointCut()")
    public void autoFill(JoinPoint joinPoint){
        log.info("公共字段填充");
        Object[] args = joinPoint.getArgs();
        //防御性编程
        if (args == null || args.length == 0) {
            return;
        }
        //获取天聪填充参数
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);
        OperationType value = annotation.value();

//        Long currentId = BaseContext.getCurrentId();
        LocalDateTime now = LocalDateTime.now();


        Object entity = args[0];
        try {
            if (value == OperationType.UPDATE) {
//                Method updateUser = args[0].getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                Method updateTime = args[0].getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);

//                updateUser.invoke(entity, currentId);
                updateTime.invoke(entity, now);

            } else if (value == OperationType.INSERT) {
//                Method createUser = args[0].getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method createTime = args[0].getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
//                Method updateUser = args[0].getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                Method updateTime = args[0].getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);

//                createUser.invoke(entity, currentId);
                createTime.invoke(entity, now);
//                updateUser.invoke(entity, currentId);
                updateTime.invoke(entity, now);
            }
        } catch (Exception e) {
            log.error("填充公共方法异常", e);
        }
    }
}
